//go:build ignore
// +build ignore

/**
 * Tencent is pleased to support the open source community by making polaris-go available.
 *
 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package main

import (
	"bufio"
	"go/format"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func main() {
	mi := make(map[string]string, 0)
	md := []string{}

	file, err := os.Open(pluginFile)
	if err != nil {
		log.Fatalf("Failed to open %s: %q", pluginFile, err)
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		if strings.HasPrefix(line, "#") {
			continue
		}

		items := strings.Split(line, ":")
		if len(items) != 2 {
			// ignore empty lines
			continue
		}
		name, repo := strings.TrimSpace(items[0]), strings.TrimSpace(items[1])

		if _, ok := mi[name]; ok {
			log.Fatalf("Duplicate entry %q", name)
		}

		md = append(md, name)
		mi[name] = pluginPath + repo // Default, unless overridden by 3rd arg

		if _, err := os.Stat(pluginFSPath + repo); err != nil { // External package has been given
			mi[name] = repo
		}
	}

	genImports("pkg/plugin/register/plugins.go", "register", mi)
}

func genImports(file, pack string, mi map[string]string) {
	openComment, err := ioutil.ReadFile(fileTemplate)
	if err != nil {
		log.Fatalf("Failed to read template file, %s\n", fileTemplate)
	}
	outs := string(openComment) + header + "package " + pack + "\n\n" + "import ("

	if len(mi) > 0 {
		outs += "\n"
	}

	outs += "// Include all plugins.\n"
	for _, v := range mi {
		outs += `_ "` + v + `"` + "\n"
	}
	outs += ")\n"

	if err := formatAndWrite(file, outs); err != nil {
		log.Fatalf("Failed to format and write: %q", err)
	}
}

func formatAndWrite(file string, data string) error {
	res, err := format.Source([]byte(data))
	if err != nil {
		return err
	}

	if err = ioutil.WriteFile(file, res, 0644); err != nil {
		return err
	}
	return nil
}

const (
	pluginPath   = "github.com/polarismesh/polaris-go/plugin/"
	pluginFile   = "plugin.cfg"
	fileTemplate = "pkg/plugin/register/plugins.temp"
	pluginFSPath = "plugin/" // Where the plugins are located on the file system
	header       = "// generated by plugin_register_generate.go; DO NOT EDIT\n\n"
)
